package com.example.a16021.myapplication;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

public class NewsActivity extends AppCompatActivity {
    ArrayList<New> list = new ArrayList();
    ListView listView;
    String picPath;
    ImageView imageView;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            //super.handleMessage(msg);
            //在handler里修改UI页面,如果handler收到消息，说明数据肯定已经取到了
            NewsAdapter newsAdapter=new NewsAdapter();
            listView.setAdapter(newsAdapter);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);
        listView = (ListView) findViewById(R.id.lv_news);
        getNewsList();//是在子线程中执行的
    }
    class NewsPicAsyncTask extends AsyncTask<String,Integer,Bitmap> {

        @Override
        protected Bitmap doInBackground(String... strings) {
            try {
                URL url=new URL(picPath);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();


                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                //发起连接
                connection.connect();
                //发起响应
                int code=connection.getResponseCode();
                if(code==200){
                    InputStream inputStream=connection.getInputStream();
                    byte[] bytes=new byte[1024];
                    int len=0;

                    ByteArrayOutputStream bos=new ByteArrayOutputStream();
                    while ((len=inputStream.read(bytes))!=-1){
                        bos.write(bytes,0,len);
                    }

                    byte[] bytesout=bos.toByteArray();

                    Bitmap bitmap= BitmapFactory.decodeByteArray(bytesout,0,bytesout.length);
                    return  bitmap;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }


        @Override
        protected void onPostExecute(Bitmap bitmap) {
            imageView.setImageBitmap(bitmap);
        }
    }
        //使用自定义适配器
    class NewsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            System.out.println(list.size());
            return list.size();
        }
        @Override
        public Object getItem(int i) {
            return null;
        }
        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            //把listview行布局文件加载进去
            View itemView = View.inflate(NewsActivity.this, R.layout.item_newslist, null);

             imageView=itemView.findViewById(R.id.img_news);
             NewsPicAsyncTask newsPicAsyncTask=new NewsPicAsyncTask();
             newsPicAsyncTask.execute();

            TextView tv_title = itemView.findViewById(R.id.tv_title);
            TextView tv_time = itemView.findViewById(R.id.tv_time);


            //给title赋值
            New news = list.get(i);
            tv_title.setText(news.title);
            tv_time.setText(news.date);
            picPath=news.thumbnail_pic_s;
            return itemView;
        }
    }
    public void getNewsList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path = "http://v.juhe.cn/toutiao/index?type=top&key=" +
                              "   3c7dea7b9b2848df8e1c5441810d5dd7";
                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);
                    connection.connect();
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        byte[] bytes = new byte[1024];//缓冲字数组
                        int len = 0;
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = inputStream.read(bytes)) != -1) {
                            bos.write(bytes, 0, len);
                        }
                        String result = new String(bos.toByteArray());
                        System.out.println(result);
                        JSONObject jo = new JSONObject(result);
                        JSONObject joResult = jo.optJSONObject("result");
                        JSONArray jaData = joResult.optJSONArray("data");
                        for (int i = 0; i < jaData.length(); i++) {
                            JSONObject joTemp = (JSONObject) jaData.get(i);
                            New news = new New();
                            news.title = joTemp.optString("title");
                            news.date = joTemp.optString("date");
                            news.author_name = joTemp.optString("author_name");
                            news.thumbnail_pic_s = joTemp.optString("thumbnail_pic_s");
                            list.add(news);
                        }
                        Message msg = Message.obtain();
                        msg.obj = list;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}